<%@ page language="java" import="java.util.*" pageEncoding="UTF-8"%>
<%@ taglib prefix="c" uri="http://java.sun.com/jsp/jstl/core"%>
<%
	String path = request.getContextPath();
	String basePath = request.getScheme()+"://"+request.getServerName()+":"+request.getServerPort()+path+"/";
%>
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
<html xmlns="http://www.w3.org/1999/xhtml">
<head>
<base href="<%=basePath%>"/>
<meta http-equiv="Content-Type" content="text/html; charset=utf-8" />
<title>权限模块-资源管理</title>
<style type="text/css">
	#tab_wrap{
		width:100%;
		padding:2px;
		height: 400px;
		border:1px solid #b3bda6;
		border-collapse:collapse;	
		margin-top:4px;	
	}
	#td_tree{
		width: 35%;
	}
	#td_list{
		width: 65%;
	}
	#td_list table{
		border-collapse: collapse;
		border:none;
		width: 100%;
	}
	
	#listTBody tr:hover {
		background-color: #9af;
		cursor: default;
	}
	.left_td{
		border-left:none;
		border-top:1px solid #b3bda6;
		border-right:1px solid #b3bda6;
		border-bottom:1px solid #b3bda6; 
	}
	
	
	form span{
		width: 220px;
		display: inline-block;
	}
	form input[type='text'],form select{
		width:120px;
		vertical-align: middle;
	}
	form .field_label{
		color:#48f;
		display:inline-block;
		min-width:60px;
		text-align: right;
	}
	
</style>
<style type="text/css">
	/* @@@@@@@@@@ 树形结构专用样式  @@@@@@@@@@ */
	.node_wrap{
		margin-left:16px;
	}
	.node:hover{
		background-color:#9af;
	}
	.node_label{
		cursor: pointer;
	}
	.node_children{
		display: none;
	}
	.node_wrap img{
		border:none;
	}
	/* @@@@@@@@@@ 树形结构专用样式  @@@@@@@@@@ */
</style>
<!-- 树形结构相关 -->
<script type="text/javascript">
var basePath = "<%=basePath%>".replace(":80/","/");//解决80端口的差异
// 节点树叶(展开或关闭)单击事件
function leafClickHandler(sender){
	if(sender.src==(basePath + "auth/image/nodeblank.png")){		
		return;
	}
	if(sender.src==(basePath + "auth/image/nodeclose.png")){
		sender.src=(basePath + "auth/image/nodeopen.png");
		sender.parentNode.parentNode.lastChild.style.display = "block";
	}else{
		sender.src=(basePath + "auth/image/nodeclose.png");
		sender.parentNode.parentNode.lastChild.style.display = "none";
	}
}
// 树形选中的节点
var selectedNode = null;
// 节点的文本标签部分单击事件
function labelClickHandler(lbl, pk){

	if(selectedNode){
		selectedNode.style.backgroundColor = lbl.parentNode.style.backgroundColor;
	}
	// 注意，selectedNode的Node指的是Tree结构的概念Node，lbl.parentNode是Html里的Node;
	selectedNode = lbl.parentNode;
	selectedNode.style.backgroundColor="#9c6";
	// 设定表单项parent值
	byId("parent").value=pk;
	// ajax刷新列表
	ajax({
		method:"GET",
		url:basePath+"auth/source/children.do?parent="+pk+"&refresh="+Math.random(),
		async:false, 
		data:null,
		success:function(http){
			// 正常执行结束
			// 将字符串转为json对象
			var sources = eval("(" + http.responseText + ")");
			// 更新列表
			var tabHtml = buildTable(sources);
			document.getElementById("td_list").innerHTML = tabHtml;
			// 未选中任何行
			selectedRow = null;
		},
		error:function(){
			// 发生错误
		},
		complete:function(http){
			// 完成执行
		},
		beforeSend:function(){
			// 发送之前
		}
	});
	
}

// 表单提交的路径
var submitPath = basePath+"auth/source/";
// 选中的表格行
var selectedRow = null;
// 
var td_list_id = "td_list";

// 增删改查
function operation(opt) {
	// 封装表单数据	
	var parts = formData(byId("source_form"));
	// 验证通过使用ajax提交
	if(verify(opt)){
		// 使用ajax无刷新提交表单			
		ajax({
			method:"POST",
			url:submitPath+opt+".do",
			async:false, 
			data:parts,
			beforeSend:function(http){
				// 发送之前，设置好HTTP头，否则会HTTP400
				http.setRequestHeader("content-length", parts.length);
				http.setRequestHeader("content-type", "application/x-www-form-urlencoded; charset=UTF-8");
			},
			success:function(http){
				// 正常执行结束
				// 刷新树形的选中节点 
				var result = eval("(" + http.responseText + ")");
				var tabHtml = buildTable(result.list);
				selectedRow = null;
				byId(td_list_id).innerHTML = tabHtml;
				// 刷新树形结构选中节点
				var tempNode = document.createElement("div");
				
				tempNode.innerHTML = result.tree;
				selectedNode.parentNode.lastChild.innerHTML=tempNode.lastChild.lastChild.innerHTML;
				
				if(selectedNode.parentNode.lastChild.firstChild==null){
					// 节点更新后，如果节点的子节点为空					
					selectedNode.firstChild.src=(basePath + "auth/image/nodeblank.png");
				}else{
					// 节点更新后，如果节点的子节点数由空变为不为空
					selectedNode.parentNode.lastChild.style.display='block';				
					selectedNode.firstChild.src=(basePath + "auth/image/nodeopen.png");					
				}	
			},
			error:function(http){
				// 发生错误
				alert(http.responseText);
			},
			complete:function(http){
				// 完成执行
			}
		});
		
	}
}

/* 切换树形结构顶点 */
function changeRoot(pk){
	location.href=basePath + "auth/source.do?pk="+pk;
}

//验证操作
function verify(opt, msg) {
	switch (opt) {
	case "save":
		if(byId("sourceid").value == ""){
			alert("资源ID不能为空");
			return false;
		}
		if(byId("sourcename").value == ""){
			alert("资源名称不能为空");
			return false;
		}
		if(byId("parent").value == ""){
			alert("请在树形结构上选择一个节点作为父节点\r\n提示：点击树形节点变为红色时即为选中");
			return false;
		}
		// 验证当前层级下资源ID是否唯一
		var trows = byId("listTBody").rows;
		for(var i=0; i<trows.length; i++){
			if(trows[i].cells[1].innerHTML==byId("sourceid").value){
				alert("当前层级下已经存在相同的资源ID");
				return false;	
			}				
		}
		return true;
	case "update":
		if(selectedRow==null){
			alert("请先在列表中选中要修改的项");
			return false;
		}
		if(byId("sourceid").value == ""){
			alert("修改的资源ID不能为空");
			return false;
		}
		if(byId("sourcename").value == ""){
			alert("修改的资源名称不能为空");
			return false;
		}
		// 验证当前层级下资源ID是否唯一
		var trows = byId("listTBody").rows;
		for(var i=0; i<trows.length; i++){
			if(trows[i].cells[0].innerHTML!=byId("pk").value && 
					trows[i].cells[1].innerHTML==byId("sourceid").value){
				alert("当前层级下已经存在相同的资源ID");
				return false;	
			}				
		}
		return true;
	case "delete":
		if(selectedRow==null){
			alert("请先在列表中选中要删除的项");
			return false;
		}
		// 删除和级联删除警告
		return true;
	}
}


// 使用资源的数组构建HTML表格
function buildTable(sources){
	// 构建表格 兼容性好，直接操tbody的话IE不技持
	var html = "<table width='100%' border='1'><thead><tr><th width='10%'>编号</th><th>资源ID</th><th>资源名称</th><th width='15%'>资源类型</th><th width='15%'>上级资源编号</th></tr></thead>";
	html += "<tbody id='listTBody'>";
	for(var i=0; i<sources.length; i++){
		html += "<tr onclick='bindToForm(this)'>";
		html += "<td>" + sources[i].pkSource + "</td>";
		html += "<td>" + sources[i].controlid + "</td>";
		html += "<td>" + sources[i].sourcename + "</td>";
		if("1"==sources[i].sourcetype){
			html += "<td>" + sources[i].sourcetype + "-导航</td>";
		}else if("2"==sources[i].sourcetype){
			html += "<td>" + sources[i].sourcetype + "-控件</td>";
		}else{
			html += "<td>" + sources[i].sourcetype + "-未知</td>";
		}		
		html += "<td>" + sources[i].parentid + "</td>";
		html += "</tr>";
	}
	html += "</tbody></table>";
	return html;
}

// 将行数据关联到表单
function bindToForm(row) {
	if (selectedRow != null) {
		// 把先前选中的行颜色还原
		selectedRow.style.backgroundColor = row.style.backgroundColor;
	}
	selectedRow = row;
	row.style.backgroundColor = "#ae8";
	byId("pk").value = $(row).find("td:nth-child(1)").text();
	byId("sourceid").value = $(row).find("td:nth-child(2)").text();
	byId("sourcename").value = $(row).find("td:nth-child(3)").text();
	if($(row).find("td:nth-child(4)").text()=="1-导航")
		byId("sourcetype1").checked=true;
	else if($(row).find("td:nth-child(4)").text()=="2-控件")
		byId("sourcetype2").checked=true;
}

/* 根据ID取得元素 */
function byId(tagId){
	return document.getElementById(tagId);
}

/* 将FORM表单数据封装为POST请求数据 */
function formData(fm){
	var array = new Array();
	for(var i=0; i<fm.elements.length; i++){
		var input = fm.elements[i];
		switch(input.type){
		case "hidden":
		case "text":
		case "password":
		case "textarea":
		case "select-one":
			array.push(input.name + "=" + encodeURIComponent (input.value));
			break;
		case "radio":
		case "checkbox":
			if(input.checked)array.push(input.name + "=" + encodeURIComponent (input.value));
			break;
		}
	}
	return array.join("&");
}

/* 模拟JQuery的AJAX请求函数 */
function ajax(settings){
	/* XMLHttpRequest或ActiveXObject */
	var xhr;
	/* 初始化方法 */
	// 初始化XMLHttpRequest
	if(window.XMLHttpRequest)
		xhr = new XMLHttpRequest();
	else
		xhr = new ActiveXObject("Microsoft.XMLHTTP");
	// 请求结束的状态处理
	xhr.onreadystatechange=function(){
		if(xhr.readyState==4){
			if(xhr.status==200){
				// 执行正常
				if(settings.success){
					settings.success(xhr);
				}
			}else{
				// 出错
				if(settings.error){
					settings.error(xhr);
				}
			}
			// 完成执行
			if(settings.complete){
				settings.complete(xhr);
			}
		}
	};
	
	// 开始向服务器发送请求
	var method="GET", url="", async=true, data=null;
	
	if(settings.method)method=settings.method;
	if(settings.url)url=settings.url;
	if(settings.async)async=settings.async;
	if(settings.data)data=settings.data;
	
	xhr.open(method, url, async);
	// 开发送请求之前
	if(settings.beforeSend){
		settings.beforeSend(xhr);
	}
	xhr.send(data);	
}
</script>




<%@include file="/WEB-INF/include/head-common.jsp" %>

</head>
<body>
<div id="main_container">
	<!-- 顶部信息 -->
	<%@include file="/WEB-INF/include/header.jsp" %>    
    <div class="main_content">
    	<!-- 导航菜单 -->
    	<%@include file="/WEB-INF/include/main-menu.jsp" %>
    
    <div class="center_content">  

	<!-- 左边栏内容 -->
    <div class="left_content">
    
  		<%@include file="/WEB-INF/include/sidebarmenu.jsp" %>
            
    </div>
      
    <!-- 右边框内容 -->
    <div class="right_content">
    	<div class="position">
	    	<div class="position_box">当前位置：<%@include file="/WEB-INF/include/sitemap.jsp" %></div>
	    </div>              
        <h2>资源管理</h2>
        <div>
       	<form id="source_form" action="" method="post">
			<input type="hidden" id="pk" name="pk"/>
			<input type="hidden" id="parent" name="parent"/>			
			<span><label class="field_label">资源ID</label><input type="text" id="sourceid" name="sourceid"/></span>
			<span><label class="field_label">资源名称</label><input type="text" id="sourcename" name="sourcename"/></span>
			<span><label class="field_label">资源类型</label>
	  			<span style="display: inline">
				<label><input type="radio" id="sourcetype1" name="sourcetype" value="1" checked="checked"/>导航</label>
	  			<label><input type="radio" id="sourcetype2" name="sourcetype" value="2"/>控件</label>
	  			</span>
		  	</span>			  	
		  	<input type="button" value="新增" onclick="operation('save')"/>
		  	<input type="button" value="修改" onclick="operation('update')"/>
		  	<input type="button" value="删除" onclick="operation('delete')"/>	
		  	<span>
		  		<label class="field_label">切换到</label>
		  		<select onchange="changeRoot(this.value);">
		  		<c:choose>
	  			<c:when test="${param.pk=='1'}">
	  				<option value="1" selected="selected">权限资源</option>
		  			<option value="2">菜单资源</option>
	  			</c:when>
	  			<c:when test="${param.pk=='2'}">
	  				<option value="1">权限资源</option>
		  			<option value="2" selected="selected">菜单资源</option>
	  			</c:when>
	  			<c:otherwise>
	  				<option value="1" selected="selected">权限资源</option>
		  			<option value="2">菜单资源</option>
	  			</c:otherwise>
		  		</c:choose>
		  		</select>
		  	</span>	
		</form>
        </div>
        <table id="tab_wrap" width="100%" cellpadding="1" cellspacing="0">
		<tr>
			<td id="td_tree" valign="top" style="border: 1px solid #b3bda6">
				<div>
				${tree }
				</div>
			</td>
			<td id="td_list" valign="top">
				<table  width="100%" cellpadding="1" cellspacing="0" border="1">
					<thead>
						<tr>
							<th width="10%">编号</th>
							<th>资源ID</th>
							<th>资源名称</th>
							<th width="15%">资源类型</th>
							<th width="15%">上级资源编号</th>
						</tr>
					</thead>
					<tbody id="listTBody">
						<c:forEach var="rs" items="${list }">
							<tr onclick="bindToForm(this)">
								<td>${rs.pkSource }</td>
								<td>${rs.controlid }</td>
								<td>${rs.sourcename }</td>
								<td>${rs.sourcetype }</td>
								<td>${rs.parentid }</td>
							</tr>
						</c:forEach>
					</tbody>
				</table>
			</td>
		</tr>
	</table>
                    
     
	</div><!-- end of right content-->
            
                    
  </div>   <!--end of center content -->               
                    

    <div class="clear"></div>
    </div> <!--end of main content-->
	
    
    <div class="footer">
    
    	<div class="left_footer">IN ADMIN PANEL | Powered by <a href="http://indeziner.com">INDEZINER</a></div>
    	<div class="right_footer"><a href="http://indeziner.com"><img src="images/indeziner_logo.gif" alt="" title="" border="0" /></a></div>
    
    </div>

</div>		
</body>
</html>
